package com.personal.website.lottery.web.controller;

import com.personal.website.lottery.web.mail.VerifyCodeSender;
import com.personal.website.lottery.web.model.Article;
import com.personal.website.lottery.web.model.User;
import com.personal.website.lottery.web.model.VerifyCode;
import com.personal.website.lottery.web.service.ArticleService;
import com.personal.website.lottery.web.service.UserService;
import com.personal.website.lottery.web.service.VerifyCodeService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

/**
 * Created by Gavin on 2016/1/24.
 */

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private ArticleService articleService;
    @Resource
    private VerifyCodeService verifyCodeService;

    @RequestMapping("/registerAction")
    public String registerAction(HttpServletRequest request,Model model) {
        String userName = request.getParameter("userName");
        String userPassword = request.getParameter("userPassword");
        String sex = request.getParameter("sex");
        String email = request.getParameter("email");
        String mobilePhoneNo = request.getParameter("mobilePhoneNo");
        List<User> dbUserList;
        dbUserList = this.userService.getUserByUserName(userName);
        if(dbUserList.size() != 0){
            model.addAttribute("backMessage","该用户名已经存在，请使用其他用户名重新注册！");
            return "backMessage";
        }
        dbUserList = this.userService.getUserByEmail(email);
        if(dbUserList.size() != 0){
            model.addAttribute("backMessage","该邮箱已被注册，请使用其他邮箱注册！");
            return "backMessage";
        }
        dbUserList = this.userService.getUserByMobilePhoneNo(mobilePhoneNo);
        if(dbUserList.size() != 0){
            model.addAttribute("backMessage","该手机号码已被注册，请使用其他手机号注册！");
            return "backMessage";
        }

        User user = new User();
        user.setUserName(userName);
        user.setEmail(email);
        user.setSex(sex);
        user.setUserPassword(userPassword);
        user.setMobilePhoneNo(mobilePhoneNo);
        user.setIp(request.getRemoteAddr());
        user.setRegisterTime(new Date());
        user.setLastLoginTime(new Date());
        userService.insertUser(user);
        model.addAttribute("backMessage","恭喜你，注册成功！");
        return "backMessage";
    }

    @RequestMapping("/loginAction")
    public String loginAction(HttpServletRequest request, HttpSession session, Model model) {
        String userName = request.getParameter("userName");
        String userPassword = request.getParameter("userPassword");
        List<User> userList = this.userService.getUserByUserName(userName);
        if(userList.size() == 0 || !userList.get(0).getUserPassword().equals(userPassword)){
            model.addAttribute("backMessage","用户名或密码不对，请重新登陆！");
            return "backMessage";
        } else{
            session.setAttribute("userName",userName);
            session.setAttribute("userId",userList.get(0).getId());
        }
        return "redirect:/index";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("userName");
        return "redirect:/index";
    }

    @RequestMapping("/forwardCreateArticle")
    public String forwardCreateArticle() {
        return "createArticle";
    }

    @RequestMapping("/personalHomePage")
    public String personalHomePage(HttpSession session) {
        int userId = (Integer) session.getAttribute("userId");
        User user = this.userService.getUserById(userId);
        return "personalHomePage";
    }

    @RequestMapping("/msgBox")
    public String msgBox() {
        return "msgBox";
    }

    @RequestMapping("/personalInfo")
    public String personalInfo(HttpSession session,Model model) {
        int userId = (Integer) session.getAttribute("userId");
        model.addAttribute("user",this.userService.getUserById(userId));
        return "personalInfo";
    }

    @RequestMapping("/issuedArticles")
    public String issuedArticles(HttpSession session,Model model) {
        int userId = (Integer) session.getAttribute("userId");
        model.addAttribute("articles",this.articleService.getIssuedArticlesByUserId(userId,30));
        return "issuedArticles";
    }

    @RequestMapping("/commentedArticles")
    public String commentedArticles(HttpSession session,Model model) {
        int userId = (Integer) session.getAttribute("userId");
        model.addAttribute("articles",this.articleService.getCommentedArticlesByUserId(userId,30));
        return "commentedArticles";
    }

    @RequestMapping("/editPassword")
    public String editPassword(HttpSession session,HttpServletRequest request,Model model) {
        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");
        String newPasswordAgain = request.getParameter("newPasswordAgain");
        int userId = (Integer) session.getAttribute("userId");

        if (! newPassword.equals(newPasswordAgain)) {
            model.addAttribute("backMessage","密码两次输入不一样，请重新输入！");
            return "backMessage";
        }
        User user = this.userService.getUserById(userId);
        if(! user.getUserPassword().equals(oldPassword)){
            model.addAttribute("backMessage","旧密码输入不对，请重新输入！");
            return "backMessage";
        }
        user.setUserPassword(newPassword);
        if(this.userService.updateUser(user)){
            model.addAttribute("backMessage","密码修改成功！");
            return "backMessage";
        }
        model.addAttribute("backMessage","系统出现未知异常，您的密码修改可能不成功！");
        return "backMessage";
    }

    @RequestMapping("/sendVerifyCode")
    @ResponseBody
    public String sendVerifyCode(HttpServletRequest request){
        String userName = request.getParameter("userName");
        String email = request.getParameter("email");
        if(!this.userService.validateUserInfo(userName, email)) {
            return "用户名和邮箱不匹配！";
        }
        try {
            String code = VerifyCodeSender.sendVerifyCode(email);
            VerifyCode verifyCode = new VerifyCode();
            verifyCode.setUserName(userName);
            verifyCode.setEmail(email);
            verifyCode.setVerifyCode(code);
            verifyCode.setCreateTime(new Date());

            this.verifyCodeService.insertVerifyCode(verifyCode);
        } catch (Exception e) {
            e.printStackTrace();
            return "邮件发送失败，请联系管理员！";
        }

        return "发送成功，请查收收件箱或垃圾箱邮件（可能有1-2分钟延迟）。";
    }

    @RequestMapping("/forgetPasswordAction")
    public String forgetPasswordAction(HttpServletRequest request,HttpSession session,Model model){
        String userName = request.getParameter("userName");
        String email = request.getParameter("email");
        String verifyCode = request.getParameter("verifyCode");
        Date endDate = new Date();
        endDate.setTime(endDate.getTime() - 3600000);

        if(this.verifyCodeService.validate(userName,email,verifyCode,endDate)) {
            session.setAttribute("forgetPasswordUserName",userName);
            return "editForgetPassword";
        }
        model.addAttribute("backMessage","验证码有误，或已经过期，请重新尝试！");
        return "backMessage";
    }

    @RequestMapping("/editForgetPassword")
    public String editForgetPassword(HttpServletRequest request,HttpSession session, Model model){
        String newPassword = request.getParameter("newPassword");
        String newPasswordAgain = request.getParameter("newPasswordAgain");
        String userName = (String) session.getAttribute("forgetPasswordUserName");

        if (! newPassword.equals(newPasswordAgain)) {
            model.addAttribute("backMessage","密码两次输入不一样，请重新输入！");
            return "backMessage";
        }
        try {
            User user = this.userService.getUserByUserName(userName).get(0);
            user.setUserPassword(newPassword);
            this.userService.updateUser(user);
        } catch (Exception e) {
            model.addAttribute("backMessage","出现未知异常，修改失败，请重新尝试！");
            return "backMessage";
        }
        session.removeAttribute("forgetPasswordUserName");
        model.addAttribute("backMessage","修改成功");
        return "backMessage";
    }

}
